package com.hxzy.tms.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.hxzy.tms.dao.BaseDao.Params;
import com.hxzy.tms.dao.ProjectDao;
import com.hxzy.tms.dao.TaskDao;
import com.hxzy.tms.dao.TeamDao;
import com.hxzy.tms.dao.TeamUserDao;
import com.hxzy.tms.dao.UserDao;
import com.hxzy.tms.dao.UserTaskDao;
import com.hxzy.tms.entity.Project;
import com.hxzy.tms.entity.Task;
import com.hxzy.tms.entity.Team;
import com.hxzy.tms.entity.TeamUser;
import com.hxzy.tms.entity.User;
import com.hxzy.tms.entity.UserTask;
import com.hxzy.tms.service.ServiceResult;
import com.hxzy.tms.service.TaskService;
import com.hxzy.tms.session.SessionHolder;

public class TaskServiceImpl implements TaskService {

	private TaskDao taskDao;
	private ProjectDao projectDao;
	private TeamDao teamDao;
	private TeamUserDao teamUserDao;
	private UserTaskDao userTaskDao;
	private UserDao userDao;
	
	public ServiceResult<List<Task>> read(long id) {
		// TODO Auto-generated method stub
		List<Task> list=taskDao.read("from Task where team.id =:id", new Params("id", id));
		return new ServiceResult<List<Task>>(1,list);
	}
	
	 public ServiceResult<List<User>> memberList(Long teamId){
	    	List<User> memberList=teamUserDao.teamUsers(teamId);
	    	return new ServiceResult<List<User>>(1,memberList);
	    }

	//任务提交列表
	public ServiceResult<List<UserTask>> commitList(long teamId,long taskId){
		List<UserTask> list=userTaskDao.read("from UserTask where team.id =:teamId and task.id= :taskId", new Params("teamId",teamId ),new Params("taskId", taskId));
		for(UserTask userTask:list){
			List<User> userList=userDao.read("from User where id=:id", new Params("id",userTask.getUser().getId()));
			for(User user:userList){
			if(userTask.getStatus()==1){
				return new ServiceResult<List<UserTask>>(1,null,user.getNickname());
			}
			}
		}
		
		return new ServiceResult<List<UserTask>>(1,list);
	}
	public ServiceResult<Task> update(Long id, Long projectId, Long teamId, String title, String desc,
			String attachmentUrl, Date gmtBegin, Date gmtEnd) {
		if(taskDao.read(Task.class, id)!=null
				&&!taskDao.read(Task.class, id).getUidCreate().equals(SessionHolder.get())){
			return new ServiceResult<Task>(-5,null,"只能修改自己团队的任务");
		}
		return saveOrUpdate(id, projectId, teamId, title, desc, attachmentUrl, gmtBegin, gmtEnd);
	}

	public ServiceResult<Task> create(Long projectId, Long teamId, String title, String desc, String attachmentUrl,
			Date gmtBegin, Date gmtEnd) {
		return saveOrUpdate(null, projectId, teamId, title, desc, attachmentUrl, gmtBegin, gmtEnd);
	}

	public ServiceResult<Task> saveOrUpdate(Long id, Long projectId, Long teamId, String title, String desc,
			String attachmentUrl, Date gmtBegin, Date gmtEnd) {
		//判断字段是否为空
		if(projectId<0){
			throw new IllegalArgumentException("project id must more than 0");
		}
		if(teamId<0){
			throw new IllegalArgumentException("team id must more than 0");
		}
		if(StringUtils.isBlank(title)){
			throw new IllegalArgumentException("title is null or empty");
		}
		if(StringUtils.isBlank(desc)){
			throw new IllegalArgumentException("desc is null or empty");
		}
		if(SessionHolder.get().getId()==null){
			return new ServiceResult<Task>(-3,null,"必须登录才能创建任务");
		}
		if(gmtBegin.getTime()>=gmtEnd.getTime()){
			return new ServiceResult<Task>(-1,null,"开始时间必须大于结束时间");
		}
		if(!teamDao.read(Team.class, teamId).getUidCreate().getId().equals(SessionHolder.get().getId())){
			return new ServiceResult<Task>(-4,null,"你不是团队创建者，不能创建任务");
		}
		Task task=new Task();
		Calendar cal=Calendar.getInstance();
		cal.setTime(gmtBegin);
		task.setGmtStartYear(cal.get(Calendar.YEAR));
		task.setGmtStartMonth(cal.get(Calendar.MONTH));
		task.setGmtStartDate(cal.get(Calendar.DATE));
		cal.setTime(gmtEnd);
		task.setGmtFinishedDate(cal.get(Calendar.DATE));
		task.setGmtFinishedMonth(cal.get(Calendar.MONTH));
		task.setGmtFinishedYear(cal.get(Calendar.YEAR));
		task.setTeam(teamDao.read(Team.class, teamId));
		task.setProject(projectDao.read(Project.class, projectId));
		task.setDesc(desc);
		task.setGmtStart(gmtBegin.getTime()/1000);
		task.setGmtFinished(gmtEnd.getTime()/1000);
		task.setUidCreate(SessionHolder.get());
		task.setUidModified(SessionHolder.get());
		task.setTitle(title);
		task.setAttachmentUrl(attachmentUrl);
		if(id!=null){
			task.setId(id);
			task.setGmtModified(System.currentTimeMillis()/1000);
			taskDao.update(task);
		}else{
			task.setGmtModified(System.currentTimeMillis()/1000);
			task.setGmtCreate(System.currentTimeMillis()/1000);
			taskDao.create(task);
		}
		//增加任务至user_task表
				UserTask userTask=new UserTask();
				List<TeamUser> teamList=teamUserDao.read("from TeamUser where team.id= :teamId", new Params("teamId", teamId));
				for(TeamUser teamUser:teamList){
					userTask.setGmtCreate(System.currentTimeMillis()/1000);
					userTask.setGmtModified(System.currentTimeMillis()/1000);
					userTask.setUidCreate(SessionHolder.get());
					userTask.setUidModified(SessionHolder.get());
					userTask.setTeam(teamUser.getTeam());
					userTask.setUser(SessionHolder.get());
					userTask.setStatus(1L);
					userTask.setProject(projectDao.read(Project.class, projectId));
					userTask.setTask(task);
					userTaskDao.create(userTask);
				}
		return new ServiceResult<Task>(1,task);
	}
	
	

	public ServiceResult<Task> delete(Task task){
		int result=taskDao.delete(task);
		if(result==0){
			return new ServiceResult<Task>(1);
		}
		return new ServiceResult<Task>(-1,null,"delete failed");
		
	}
	
	
	//提交任务
	public ServiceResult<UserTask> update(Long taskId, String attachmentUrl) {
		// TODO Auto-generated method stub
		if(taskId<=0){
			throw new IllegalArgumentException("task id must more than 0");
		}
		if(StringUtils.isBlank(attachmentUrl)){
			throw new IllegalArgumentException("attachmentUrl is null or empty");
		}
	
		
		List<UserTask> userList=userTaskDao.read("from UserTask where task.id= :taskId and user.id =:uid", new Params("taskId", taskId),new Params("uid", SessionHolder.get().getId()));
		
		Task task=taskDao.read(Task.class, taskId);
		if(!userList.isEmpty()){
			if(task.getGmtFinished()<=System.currentTimeMillis()/1000){
			UserTask userTask=userList.get(0);
			userTask.setAttachmentUrl(attachmentUrl);
			userTask.setStatus(2L);
			userTaskDao.update(userTask);
			}else{
				return new ServiceResult<UserTask>(-2,null,"你已超时,提交任务失败");
			}
		}else{
			return new ServiceResult<UserTask>(-3,null,"");
		}
		return new ServiceResult<UserTask>(1);
	}
	
	  public ServiceResult<List<UserTask>> taskList(Long userId) {
	      List<UserTask> taskList=userTaskDao.read("from UserTask where user.id=:userId", new Params("userId", userId));
	        return new ServiceResult<List<UserTask>>(1,taskList);
	    }


	  public ServiceResult<List<UserTask>> userTasks(long taskId) {
	        List<UserTask> userTasks = userTaskDao.read(" from UserTask where task.id = :taskId order by gmtCreate desc",
	                new Params("taskId", taskId));
	        return new ServiceResult<List<UserTask>>(1, userTasks);
	    }
	public UserTaskDao getUserTaskDao() {
		return userTaskDao;
	}

	public void setUserTaskDao(UserTaskDao userTaskDao) {
		this.userTaskDao = userTaskDao;
	}

	public TeamUserDao getTeamUserDao() {
		return teamUserDao;
	}

	public void setTeamUserDao(TeamUserDao teamUserDao) {
		this.teamUserDao = teamUserDao;
	}

	public TaskDao getTaskDao() {
		return taskDao;
	}

	public void setTaskDao(TaskDao taskDao) {
		this.taskDao = taskDao;
	}

	public ProjectDao getProjectDao() {
		return projectDao;
	}

	public void setProjectDao(ProjectDao projectDao) {
		this.projectDao = projectDao;
	}

	public TeamDao getTeamDao() {
		return teamDao;
	}

	public void setTeamDao(TeamDao teamDao) {
		this.teamDao = teamDao;
	}

  
	
}
